
//
//  YMSOAuthController.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/15.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SVProgressHUD
//保存路径
let Userpath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("YMSAccount.plist")

class YMSOAuthController: UIViewController {
    //声明webview
    let mywebView = UIWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        //搭建界面
        view = mywebView
        mywebView.delegate = self
        self .setUI()
        loadOauthPage()
    }
 //---------------------------搭建界面以及处理按钮的监听事件----------------------------
    //MARK: 搭建界面
    func setUI(){
        self.title = "用户登录界面"
        self.view.backgroundColor = #colorLiteral(red: 0.9568627477, green: 0.6588235497, blue: 0.5450980663, alpha: 1)
        //添加左右两个按钮
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", imageName: "", target: self, action: #selector(back))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "获取账户", imageName: "", target: self, action: #selector(fillAcount))
    }
    //返回按钮的点击事件
   @objc private func back(){
    self.dismiss(animated: true, completion: nil)
    }
    //获取账户的点击事件
    @objc private func fillAcount(){
        let jsString = "document.getElementById('userId').value = '18237682795', document.getElementById('passwd').value = 'wsndy19940320'"
        mywebView.stringByEvaluatingJavaScript(from: jsString)
    }
    //默认上来就用webview加载一个网址
    private func loadOauthPage() {
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = URL(string: urlString)
        let req = URLRequest(url: url!)
        mywebView.loadRequest(req)
    }
    //在视图即将消失的时候,dismis掉Svp
    override func viewWillDisappear(_ animated: Bool) {
        SVProgressHUD.dismiss()
    }
}
//-----------------------------获取接口信息---------------------------------------------
//MARK: 将获取接口信息的方法放在分类中,更容易维护
extension YMSOAuthController:UIWebViewDelegate{
    //webview加载界面的时候
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //webview加载界面完成之后
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //方法返回值为true和false 返回true正常运行,否则不能
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //从请求中获得当前访问的网站
        let urlString = request.url?.absoluteString ?? ""
        let flag = "code=" //判断是否有code= 字节
        //如果获取的网络中包含这个直接
        if urlString.contains(flag) {
            //截取code
            let query = request.url?.query ?? "" //这其中包含有code信息
            //把query转换为oc字符串载进行截取
            let code = (query as NSString).substring(from: flag.characters.count)
            //print(code) //测试获取的code是否正确
            
//--------------获取到code之后就能用code去获取token(访问接口的唯一标示)---------------
            
            //需要网络模型
            YMSUserinfoViewModel.shared.loadAccessToken(code: code, finished: { (isSuccess:Bool) in
                
                if !isSuccess {
                //没有成功
                    SVProgressHUD.showError(withStatus: "检查是否连接网络")
                    return
                }
                //请求成功
                print("请求成功")
                UIApplication.shared.keyWindow?.rootViewController = YMSOAuthWellcomeController()
            })
            return false
        }
        return true
    }
}
